﻿using PLCS.App.Shared.ViewModels;
using PLCS.Application.Contracts.ConfigApp.Dtos;
using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Application.Contracts.PLCConfigApp.Dtos;
using PLCS.Client.IService.ConfigManager;
using PLCS.Client.IService.LogManager;
using PLCS.Shared.Common.Constant;

using Prism.Services.Dialogs;

using System;

using Volo.Abp.ObjectMapping;

namespace PLCS.App.ConfigManager.ViewModels.Config;

internal class ConfigDetailViewModel : HostDialogViewModel
{
    public ConfigDetailViewModel(IObjectMapper<ConfigManagerModule> objectMapper, IConfigService configService, IOperationLogService logShowService)
    {
        _objectMapper = objectMapper;
        _configService = configService;
        this._logShowService = logShowService;
    }

    private ConfigDto _model;
    private readonly IObjectMapper<ConfigManagerModule> _objectMapper;
    private readonly IConfigService _configService;
    private readonly IOperationLogService _logShowService;

    public ConfigDto Model
    {
        get { return _model; }
        set { _model = value; }
    }

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<ConfigDto>("Value");
            Title = "编辑";
        }
        else
        {
            Title = "新增";
            Model = new ConfigDto();
        }
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            var config = _objectMapper.Map<ConfigDto, ConfigEditDto>(Model);
            if (config.Id != Guid.Empty)
                await _configService.UpdateAsync(config);
            else
                await _configService.CreateAsync(config);

            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
        finally { SavebuttonIsEnabled = true; }
    }
}